package com.example.lotterysystem.controller;

import com.example.lotterysystem.common.pojo.CommonResult;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.DrawPrizeParam;
import com.example.lotterysystem.controller.param.ShowWinningRecordsParam;
import com.example.lotterysystem.controller.result.WinningRecordsResult;
import com.example.lotterysystem.service.DrawPrizeService;
import com.example.lotterysystem.service.dto.WinningRecordsResultDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DrawPrizeController {

    private static final Logger logger= LoggerFactory.getLogger(DrawPrizeController.class);

    @Autowired
    private DrawPrizeService drawPrizeService;

    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(@Validated @RequestBody DrawPrizeParam param){
        logger.info("drawPrize DrawPrizeParam:{}",
                JacksonUtil.writeValueAsString(param));
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }

    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordsResult>> showWinningRecords(
            @Validated @RequestBody ShowWinningRecordsParam param){
        logger.info("showWinningRecords ShowWinningRecordsParam:{}",
                JacksonUtil.writeValueAsString(param));
        List<WinningRecordsResultDTO> winningRecordsDTOList = drawPrizeService.getWinningRecords(param);
        return CommonResult.success(convertToWinningRecordsResult(winningRecordsDTOList));
    }

    private List<WinningRecordsResult> convertToWinningRecordsResult(
            List<WinningRecordsResultDTO> winningRecordsDTOList) {
        if (CollectionUtils.isEmpty(winningRecordsDTOList)){
            return Arrays.asList();
        }
        return winningRecordsDTOList.stream()
                .map(winningRecordsResultDTO -> {
                    WinningRecordsResult result = new WinningRecordsResult();
                    result.setWinnerId(winningRecordsResultDTO.getWinnerId());
                    result.setWinnerName(winningRecordsResultDTO.getWinnerName());
                    result.setPrizeName(winningRecordsResultDTO.getPrizeName());
                    result.setPrizeTier(winningRecordsResultDTO.getPrizeTier().getMessage());
                    result.setWinningTime(winningRecordsResultDTO.getWinningTime());
                    return result;
                }).collect(Collectors.toList());
    }

}
